package com.btex.app;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.verificationsdk.ui.IActivityCallback;
import com.alibaba.verificationsdk.ui.VerifyActivity;
import com.alibaba.verificationsdk.ui.VerifyType;
import com.btex.app.push.SendPushInfo;
import com.btex.app.tools.LogUtil;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.Util;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseActivity {

    protected static final String TAG = "LoginActivity";
    private EditText etEmailMobile, etPsw, etIvCode, etGoogleCode;
    private LinearLayout llIvCode;
    private ImageView ivCode;
    private Button btnLogin;
    private TextView tvForgotPsw, tvRegist;
    private boolean isGoogle_code, isIv_code;
    private ImageLoader imageLoader;
    private PreferencesCookieStore cookieStore;
    private String token, userName;

    private MicroAVLIDialog mMicroAVLIDialog;

    private void assignViews() {
        etEmailMobile = (EditText) findViewById(R.id.etEmailMobile);
        etPsw = (EditText) findViewById(R.id.etPsw);
        llIvCode = (LinearLayout) findViewById(R.id.ll_ivCode);
        etIvCode = (EditText) findViewById(R.id.et_ivCode);
        ivCode = (ImageView) findViewById(R.id.iv_code);
        etGoogleCode = (EditText) findViewById(R.id.et_googleCode);
        btnLogin = (Button) findViewById(R.id.btnLogin);
        tvForgotPsw = (TextView) findViewById(R.id.tvForgotPsw);
        tvRegist = (TextView) findViewById(R.id.tvRegist);

        tvForgotPsw.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        ivCode.setOnClickListener(this);
        tvRegist.setOnClickListener(this);
        imageLoader = ImageLoader.getInstance();
        cookieStore = new PreferencesCookieStore(cxt);
        etEmailMobile.addTextChangedListener(new MyWatcher());
        etPsw.addTextChangedListener(new MyWatcher());
        etIvCode.addTextChangedListener(new MyWatcher());
        etGoogleCode.addTextChangedListener(new MyWatcher());

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mMicroAVLIDialog = new MicroAVLIDialog(this);
        assignViews();
        initData();
    }


    @Override
    public void setData() {
        userName = sp.getString(Config.KEY_USER_ACCOUNT, null);
        if (userName != null)
            etEmailMobile.setText(userName);
        tv_menu.setText(getString(R.string.regist));
        tv_title.setText(getString(R.string.login));
    }


    @Override
    public void onClick(View v) {
        Intent i;
        switch (v.getId()) {
            case R.id.tv_menu:
                i = new Intent(cxt, RegistActivity.class);
                startActivity(i);
                finish();
                break;
            case R.id.btnLogin:

                if (TextUtils.isEmpty(etEmailMobile.getText().toString().trim())) {
                    Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.red), getString(R.string.input_counter));
                    return;
                }

                if (TextUtils.isEmpty(etPsw.getText().toString().trim())) {

                    Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.red), getString(R.string.input_psw));
                    return;
                }

                callSDKDoVerification(VerifyType.NOCAPTCHA, null);
//                toLogin(isGoogle_code, isIv_code, "");

                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tvRegist:
                i = new Intent(cxt, RegistActivity.class);
                startActivity(i);
                finish();
                break;
            case R.id.iv_code:
                Toast.makeText(cxt, "点击了", Toast.LENGTH_SHORT).show();
                imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
                break;
            case R.id.tvForgotPsw:
                i = new Intent(cxt, WebActivity.class);
                i.putExtra("web_url", Config.URL + "pub/user_get_password");
                startActivity(i);
                break;
        }
    }
    /**
     * 点击确定 登录
     */

    /**
     * 登录
     *
     * @param google_code true  需要谷歌验证码
     * @param iv_code     true     需要图片验证码
     */
    private void toLogin(boolean google_code, final boolean iv_code, String verifytoken) {
        mMicroAVLIDialog.show();
        final String account = etEmailMobile.getText().toString();
        String psw = etPsw.getText().toString();
        final RequestParams params = new RequestParams();

        HashMap<String, String> stringStringHashMap = new HashMap<>();

        params.addHeader("app-version", Config.VERSION);
        params.addHeader("channel", MyApplication.mApp.getApplicationMetaData("CXD_CHANNEL_ID"));
        params.addHeader("myclient", "android");


        params.addBodyParameter(Config.KEY_USER_ACCOUNT, account);
        params.addBodyParameter(Config.KEY_USER_PSW, psw);
        params.addBodyParameter("myclient", "android");
        params.addBodyParameter("code_sessionid", verifytoken);
        params.addBodyParameter("code_scene", "register");


        stringStringHashMap.put(Config.KEY_USER_ACCOUNT, account);
        stringStringHashMap.put(Config.KEY_USER_PSW, psw);
        stringStringHashMap.put("code_sessionid", verifytoken);
        stringStringHashMap.put("code_scene", "register");

        if (google_code) {
            params.addBodyParameter(Config.KEY_AUTH_NUM, etGoogleCode.getText().toString());

            stringStringHashMap.put(Config.KEY_AUTH_NUM, etGoogleCode.getText().toString());
        }
        if (iv_code) {
            params.addBodyParameter(Config.KEY_CHECK_PIC, etIvCode.getText().toString());
            stringStringHashMap.put(Config.KEY_CHECK_PIC, etIvCode.getText().toString());
        }


        final HttpUtils httpUtils = new HttpUtils();
        httpUtils.configCookieStore(cookieStore);
        httpUtils.configCurrentHttpCacheExpiry(10000);


//        OkGo.<String>post(Config.URL_USER_LOGIN).params(stringStringHashMap).execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//
//                String result = response.body();
//
//                token = cookieStore.getCookie(Config.TOKEN) == null ? null : cookieStore.getCookie(Config.TOKEN).getValue();
//                try {
//                    JSONObject jsonObj = new JSONObject(result);
//                    if ("1".equals(jsonObj.getString(Config.KEY_CODE))) {
//                        mMicroAVLIDialog.dismiss();
//                        //绑定推送
//                        new SendPushInfo(sp.getString("baiduID", null), cxt, "baidu");
//                        new SendPushInfo(sp.getString("xiaomiID", null), cxt, "xiaomi");
//
//                        sp.putString(Config.TOKEN, jsonObj.getJSONObject(Config.KEY_DATA).getString(Config.TOKEN));
//                        sp.putString(Config.KEY_USER_ACCOUNT, account);
//                        sp.putBoolean(Config.KEY_IS_LOGIN, true);
//                        sp.putString("check", sp.getString("check", "0"));
////                        SnackbarShow(getString(R.string.login_suess));
//                        Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.bg_green), getString(R.string.login_suess));
////                        Intent i = new Intent(cxt, TabsActivity.class);
////                        startActivity(i);
//                        finish();
//
//                    } else if ("-5".equals(jsonObj.getString(Config.KEY_CODE))) {
//                        mMicroAVLIDialog.dismiss();
////                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
////                        SnackbarShow(jsonObj.getString("info"));
//                        Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.red), jsonObj.getString("info"));
//                        etGoogleCode.setVisibility(View.VISIBLE);
//                        isGoogle_code = true;
//                        btnLogin.setBackgroundResource(R.color.app_k);
//                        btnLogin.setClickable(false);
//                    } else if ("-6".equals(jsonObj.getString(Config.KEY_CODE))) {
//                        mMicroAVLIDialog.dismiss();
////                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
////                        SnackbarShow(jsonObj.getString("info"));
//                        llIvCode.setVisibility(View.VISIBLE);
//                        imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
//                        isIv_code = true;
//                        btnLogin.setBackgroundResource(R.color.app_k);
//                        btnLogin.setClickable(false);
//                    } else if ("-1".equals(jsonObj.getString(Config.KEY_CODE))) {
//                        mMicroAVLIDialog.dismiss();
////                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
////                        SnackbarShow(jsonObj.getString("info"));
//                        Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.red), jsonObj.getString("info"));
//                        if (llIvCode.getVisibility() != View.GONE) {
//                            imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
//                            etIvCode.setText("");
//                        }
//                    }
//                } catch (Exception e) {
//                    LogUtil.e(TAG, e.toString());
//                }
//
//            }
//        });


        httpUtils.send(HttpRequest.HttpMethod.POST, Config.URL_USER_LOGIN, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                Log.i("wlkewefijo", result);
                token = cookieStore.getCookie(Config.TOKEN) == null ? null : cookieStore.getCookie(Config.TOKEN).getValue();
                try {
                    JSONObject jsonObj = new JSONObject(result);
                    if ("1".equals(jsonObj.getString(Config.KEY_CODE))) {
                        mMicroAVLIDialog.dismiss();
                        //绑定推送
                        new SendPushInfo(sp.getString("baiduID", null), cxt, "baidu");
                        new SendPushInfo(sp.getString("xiaomiID", null), cxt, "xiaomi");

                        sp.putString(Config.TOKEN, jsonObj.getJSONObject(Config.KEY_DATA).getString(Config.TOKEN));
                        sp.putString(Config.KEY_USER_ACCOUNT, account);
                        sp.putBoolean(Config.KEY_IS_LOGIN, true);
                        sp.putString("check", sp.getString("check", "0"));
//                        SnackbarShow(getString(R.string.login_suess));
                        Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.bg_green), getString(R.string.login_suess));
//                        Intent i = new Intent(cxt, TabsActivity.class);
//                        startActivity(i);
                        finish();

                    } else if ("-5".equals(jsonObj.getString(Config.KEY_CODE))) {
                        mMicroAVLIDialog.dismiss();
//                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
//                        SnackbarShow(jsonObj.getString("info"));
                        Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.red), jsonObj.getString("info"));
                        etGoogleCode.setVisibility(View.VISIBLE);
                        isGoogle_code = true;
                        btnLogin.setBackgroundResource(R.color.app_k);
                        btnLogin.setClickable(false);
                    } else if ("-6".equals(jsonObj.getString(Config.KEY_CODE))) {
                        mMicroAVLIDialog.dismiss();
//                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
//                        SnackbarShow(jsonObj.getString("info"));
                        llIvCode.setVisibility(View.VISIBLE);
                        imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
                        isIv_code = true;
                        btnLogin.setBackgroundResource(R.color.app_k);
                        btnLogin.setClickable(false);
                    } else if ("-1".equals(jsonObj.getString(Config.KEY_CODE))) {
                        mMicroAVLIDialog.dismiss();
//                        Toast.makeText(cxt, jsonObj.getString("info"), Toast.LENGTH_SHORT).show();
//                        SnackbarShow(jsonObj.getString("info"));
                        Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.red), jsonObj.getString("info"));
                        if (llIvCode.getVisibility() != View.GONE) {
                            imageLoader.displayImage(Config.URL_CHECK_PIC + token, ivCode);
                            etIvCode.setText("");
                        }
                    }
                } catch (Exception e) {
                    LogUtil.e(TAG, e.toString());
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                LogUtil.e(TAG, "error:" + error + "   msg:" + msg);
            }
        });

    }

    private class MyWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            if (!TextUtils.isEmpty(etEmailMobile.getText()) && !TextUtils.isEmpty(etPsw.getText())) {
                if (llIvCode.getVisibility() == View.GONE) {
                    if (etGoogleCode.getVisibility() == View.GONE || !TextUtils.isEmpty(etGoogleCode.getText())) {
                        btnLoginClickable();
                    } else {
                        btnLoginUnClickable();
                    }
                } else {
                    if (etGoogleCode.getVisibility() == View.GONE) {
                        if (!TextUtils.isEmpty(etIvCode.getText())) {
                            btnLoginClickable();
                        } else {
                            btnLoginUnClickable();
                        }
                    } else {
                        if (!TextUtils.isEmpty(etGoogleCode.getText()) && !TextUtils.isEmpty(etIvCode.getText())) {
                            btnLoginClickable();
                        } else {
                            btnLoginUnClickable();
                        }
                    }
                }

            } else {
                btnLoginUnClickable();
            }
        }

    }

    private void btnLoginClickable() {
        btnLogin.setBackgroundResource(R.drawable.selector_btn_app_color);
        btnLogin.setClickable(true);
        btnLogin.setTextColor(cxt.getResources().getColor(R.color.white));
    }

    private void btnLoginUnClickable() {
        btnLogin.setBackgroundResource(R.color.app_k);
        btnLogin.setClickable(false);
        btnLogin.setTextColor(cxt.getResources().getColor(R.color.white));
    }
//
//    long exitTime = 0;
//
//    @Override
//    public boolean dispatchKeyEvent(KeyEvent event) {
//
//        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
//                && event.getAction() == KeyEvent.ACTION_DOWN) {
//            if ((System.currentTimeMillis() - exitTime) > 2000) {
//                Toast.makeText(LoginActivity.this, "再按一次退出BTEX", Toast.LENGTH_SHORT).show();
//                exitTime = System.currentTimeMillis();
//            } else {
//                sp.putString("check", "0");
//                System.exit(0);
//                finish();
//            }
//            return true;
//        }
//        return super.dispatchKeyEvent(event);
//    }


    /**
     * 验签主调用功能函数
     *
     * @param selectedIndex 验证类型，目前只支持 滑动验证
     * @param data          验证需要传入的数据，默认传 null
     */
    public void callSDKDoVerification(VerifyType selectedIndex, String data) {
        if (data == null) {
            VerifyActivity.startSimpleVerifyUI(LoginActivity.this, selectedIndex, "0335", null, new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {

//                    SnackbarShow("请完成安全验证");
                    Util.showSnachBar(LoginActivity.this, getResources().getColor(R.color.red), "请完成安全验证");
                }

                @Override
                public void onResult(int retInt, Map code) {

                    LoginActivity.this.verifyDidFinishedWithResult(retInt, code);
                }
            });
        } else {
            Map<String, String> params = new HashMap<>();
            //设置params，目前只需设置 VerifyActivity.APP_DATA
            params.put(VerifyActivity.APP_DATA, data);
            VerifyActivity.startVerifyUI(LoginActivity.this, params, selectedIndex, "0335", null, new IActivityCallback() {
                @Override
                //返回按钮回调
                public void onNotifyBackPressed() {

                }

                @Override
                public void onResult(int retInt, Map code) {
                    LoginActivity.this.verifyDidFinishedWithResult(retInt, code);
                }
            });
        }
    }

    /**
     * 验签回调功能函数
     *
     * @param retInt 返回码
     * @param code   返回内容
     */
    public void verifyDidFinishedWithResult(int retInt, Map code) {
        switch (retInt) {
            case VerifyActivity.VERIFY_SUCC:

                String sessionID = (String) code.get("sessionID");
                toLogin(isGoogle_code, isIv_code, sessionID);

                break;

            case VerifyActivity.VERIFY_FAILED:
                VerifyActivity.finishVerifyUI();

                break;
        }
    }

}
